package com.kotlin.book.fragments

import android.animation.ObjectAnimator
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.adapter.ClassLeftItemAdapter
import com.kotlin.book.adapter.ClassRightItemAdapter
import com.kotlin.book.adapter.ClassScreeningItemAdapter
import com.kotlin.book.api.BookApi
import com.kotlin.book.api.TypeApi
import com.kotlin.book.databinding.FragmentClassBinding
import com.kotlin.book.entry.Book
import com.kotlin.book.entry.Type
import com.kotlin.book.util.Util

class ClassFragment : Fragment() {
    private lateinit var binding: FragmentClassBinding
    private var getBookParam = mutableMapOf("page" to 1, "pageSize" to 10)
    private var bookList: MutableList<Book> = mutableListOf()
    private var navbarList: List<Type> = mutableListOf()
    private var navbarCurrentIndex: Int = 0
    private var classList: List<Type> = mutableListOf()
    private var classListCurrentIndex: Int = 0


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentClassBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //获取父级分类
        TypeApi.getClassType(mapOf("pid" to 0)) { response ->
            response?.data?.let {
                activity?.runOnUiThread {
                    navbarList = it
                    getClassType()
                    //设置文字样式
                    for (type in navbarList) {
                        val textView = TextView(context).apply {
                            layoutParams = LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.WRAP_CONTENT,
                                Util.dpToPx(27, requireContext())
                            )
                            setPadding(
                                Util.dpToPx(10, context),
                                Util.dpToPx(0, context),
                                Util.dpToPx(10, context),
                                Util.dpToPx(0, context)
                            )
                            textSize = 16f
                            text = type.name

                            setOnClickListener {
                                val index = binding.navbarBox.indexOfChild(it)
                                setTextViewStyle(index)
                                navbarCurrentIndex = index
                                classListCurrentIndex = 0
                                (binding.classLeft.adapter as ClassLeftItemAdapter).setCurrentIndex(
                                    0
                                )
                                getClassType()
                            }
                        }
                        binding.navbarBox.addView(textView)
                        //设置第一个选中
                        setTextViewStyle(0)
                    }
                }
            }
        }
        // 配置打开或关闭侧边抽屉的开关
        binding.screening.setOnClickListener {
            if (binding.classDrawer.isDrawerOpen(GravityCompat.END)) {
                binding.classDrawer.closeDrawer(GravityCompat.END)
            } else {
                rotateIcon(binding.screeningIcon, 180f)
                binding.classDrawer.openDrawer(GravityCompat.END)
            }
        }
        // 配置抽屉的点击监听旋转图标
        binding.classDrawer.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
            override fun onDrawerOpened(drawerView: View) {}
            override fun onDrawerClosed(drawerView: View) {
                rotateIcon(binding.screeningIcon, 0f)
            }

            override fun onDrawerStateChanged(newState: Int) {}
        })
        //滚动到底部事件
        binding.classRight.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val totalItemCount = layoutManager.itemCount
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                if (lastVisibleItemPosition == totalItemCount - 1) {
                    getBookList()
                }
            }
        })
        //抽屉筛选分类
        val screeningTypeList = listOf("都市现纯", "幻想现纯", "古代纯爱", "悬疑游戏")
        binding.typeBox.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.typeBox.adapter = ClassScreeningItemAdapter(screeningTypeList) { index ->
            Log.d("分类", "index: $index")
        }

        //抽屉更新进度分类
        val screeningUpdateList = listOf("连载", "完结")
        val isEndList = listOf(0, 1)
        binding.updateBox.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.updateBox.adapter = ClassScreeningItemAdapter(screeningUpdateList) { index ->
            index?.let {
                getBookParam["isEnd"] = isEndList[index]
            }
        }

        //抽屉字数分类
        val screeningWordsList =
            listOf("30万字以下", "30-50万字", "50-80万字", "80-100万字", "100万字以上")
        val wordList = listOf(0, 30, 50, 80, 100)
        binding.wordsBox.layoutManager = GridLayoutManager(requireContext(), 3)
        binding.wordsBox.adapter = ClassScreeningItemAdapter(screeningWordsList) { index ->
            index?.let {
                getBookParam["startWord"] = wordList[index]
                if (index < 4) {
                    getBookParam["endWord"] = wordList[index + 1]
                } else {
                    getBookParam.remove("endWord")
                }
            }
        }

        binding.submit.setOnClickListener {
            updateList()
            binding.classDrawer.closeDrawer(GravityCompat.END)
        }
        binding.reset.setOnClickListener {
            (binding.typeBox.adapter as ClassScreeningItemAdapter).setCurrentIndex(null)
            (binding.updateBox.adapter as ClassScreeningItemAdapter).setCurrentIndex(null)
            (binding.wordsBox.adapter as ClassScreeningItemAdapter).setCurrentIndex(null)
            getBookParam.remove("isEnd")
            getBookParam.remove("startWord")
            getBookParam.remove("endWord")
            binding.classDrawer.closeDrawer(GravityCompat.END)
            updateList()
        }
    }

    //左侧选择栏内容
    private fun getClassType() {
        TypeApi.getClassType(mapOf("pid" to navbarList[navbarCurrentIndex].id)) { response ->
            response?.data?.let {
                classList = it
                //右侧图书
                updateList()
                activity?.runOnUiThread {
                    if (binding.classLeft.adapter == null) {
                        binding.classLeft.adapter =
                            ClassLeftItemAdapter(classList.toMutableList()) { index ->
                                classListCurrentIndex = index
                                updateList()
                            }
                    } else {
                        (binding.classLeft.adapter as ClassLeftItemAdapter).setData(classList.toMutableList())
                    }
                }
            }
        }
    }

    // 分页获取书籍列表
    private fun getBookList() {
        getBookParam["typeId"] = classList[classListCurrentIndex].id
        BookApi.getClassList(getBookParam) { response ->
            response?.data?.let {
                val page = getBookParam["page"] ?: 1
                getBookParam["page"] = page + 1
                bookList.addAll(it)
                activity?.runOnUiThread {
                    if (binding.classRight.adapter == null) {
                        binding.classRight.adapter = ClassRightItemAdapter(bookList)
                    } else {
                        (binding.classRight.adapter as ClassRightItemAdapter).setData(bookList)
                    }
                }
            }
        }
    }

    // 根据选择的分类更新右侧的书籍列表
    private fun updateList() {
        getBookParam["page"] = 1
        bookList.clear()
        getBookList()
    }

    // 旋转图标动画，参数angle为旋转角度
    private fun rotateIcon(icon: View, angle: Float) {
        ObjectAnimator.ofFloat(icon, "rotation", angle).apply {
            duration = 100 // 动画持续时间
            start()
        }
    }

    //设置头部文字选中样式
    private fun setTextViewStyle(position: Int) {
        for (i in 0 until binding.navbarBox.childCount) {
            val textView = binding.navbarBox.getChildAt(i) as TextView
            if (i == position) {
                textView.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.class_navbar_bottom)
                textView.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.primary_color
                    )
                )
                textView.setTypeface(null, Typeface.BOLD)
            } else {
                textView.background = null
                textView.setTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.text_color_primary
                    )
                )
                textView.setTypeface(null, Typeface.NORMAL)
            }
        }
    }
}